package com.example.backend.controller;

import com.example.backend.entity.Comment;
import com.example.backend.mapper.CommentMapper;
import com.example.backend.util.Result;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/comment")
public class CommentController {

    private final CommentMapper commentMapper;

    public CommentController(CommentMapper commentMapper) {
        this.commentMapper = commentMapper;
    }

    @GetMapping("/get/{id}")
    public Result<List<Comment>> select_comment_id(@PathVariable String id) {
        try {
            List<Comment> list = commentMapper.select_comment_id(id);
            if (list != null) {
                return Result.success(list);
            }
            else {
                return Result.error("404", "empty result: comment");
            }
        }
        catch (Exception e) {
            return Result.error("500", e.getMessage());
        }
    }

    @PostMapping("/upload")
    public Result<Object> insert_comment_upload(@RequestBody Map<String, Object> comment) {
        try {
            commentMapper.insert_comment_upload(
                    new Comment(
                            (String)comment.get("pid"),
                            (String)comment.get("content"),
                            (String)comment.get("username"),
                            new Timestamp(System.currentTimeMillis())
                    )
            );
            return Result.success();
        }
        catch (Exception e) {
            return Result.error("500", e.getMessage());
        }
    }

    @PostMapping("/delete")
    public Result<Object> delete_comment_id(@RequestParam Integer cid) {
        try {
            commentMapper.delete_comment_id(cid);
            return Result.success();
        }
        catch (Exception e) {
            return Result.error("500", e.getMessage());
        }
    }

}
